/*
 * Copyright [2009] [Marcin Rzeźnicki]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

package mr.go.yaxc.actions;

import mr.go.yaxc.Action;
import mr.go.yaxc.ConfigurationError;
import mr.go.yaxc.ScopeHandler;

import org.apache.commons.beanutils.BeanUtils;
import org.xml.sax.Attributes;

/**
 * This action sets property on <i>object</i> in local scope.
 * 
 * <h6>on xml element start:</h6> Nothing <h6>on xml element end:</h6> Sets
 * property on <i>object</i> in scope. Property name is taken from xml tag.
 * Property value is text of xml element converted to required type by
 * commons-beanutils converter (see http://commons.apache.org
 * /beanutils/api/index.html) <h6>prerequisites:</h6> <i>parentObject</i> set
 * <h6>attributes:</h6> none
 *<p>
 * Example:<br>
 * 
 * <pre>
 * &lt;New class=&quot;mr.go.yaxc.tests.test1.Bean&quot; id=&quot;bean&quot;&gt;
 * 		&lt;Properties&gt;
 * 			&lt;intValue&gt;5&lt;/intValue&gt;
 * 			&lt;stringValue&gt;abc&lt;/stringValue&gt;
 * 			&lt;booleanValue&gt;true&lt;/booleanValue&gt;
 * 			&lt;doubleValue&gt;0.5&lt;/doubleValue&gt;
 * 			&lt;floatValue&gt;1.25&lt;/floatValue&gt;
 * 		&lt;/Properties&gt;
 * 	&lt;/New&gt;
 * </pre>
 * 
 * </p>
 * 
 * 
 * @author Marcin Rzeźnicki
 * 
 */
public class SetProperty extends Action {

	private String propertyName;

	@Override
	public void carryOut(String name, Attributes attributes,
			ScopeHandler handler) throws Exception {
		propertyName = name;
		// common mistake
		if (Character.isUpperCase(propertyName.charAt(0))) {
			propertyName = Character.toLowerCase(propertyName.charAt(0))
					+ propertyName.substring(1);
		}
	}

	@Override
	public void processed(String body, ScopeHandler handler) throws Exception {
		final Object o = handler.parentObject();
		if (o == null) {
			throw new ConfigurationError("No object to set property of");
		}
		if (handler.getLogger().isDebugEnabled()) {
			handler.getLogger().debug("Setting property {} of object ({})",
					propertyName, o);
		}
		BeanUtils.setProperty(o, propertyName, body);

	}

}
